import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, ScrollView,
	PixelRatio, Platform,
} from 'react-native';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { LargeBtn } from '../../requirement-plan/component/Component.js';

const scale = GLOBAL.SCALE;

const optionPicSourse = require('../../../imgs/global/option.png');
const selectedPicSourse = require('../../../imgs/global/success.png');

export class AddressArrayPage extends Component {

	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '地址信息',
			headerLeft: <Common type="headLeft" onPress={() => {
				navigation.navigate('EnterpriseCreateAdditionInfo', {
					addressList: navigation.state.params.addressList
				});
			}} />,
			headerRight: <TouchableOpacity onPress={() => {
				const { navigate } = navigation;
				navigate('AddressAddPage', {
					goBack: 'AddressArrayPage',
					companyAddress: {},
					areaText: ''
				});
			}} style={{ paddingRight: 10 * scale }}><Text style={styles.text}>添加地址</Text></TouchableOpacity>,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		};
	};

	constructor(props) {
		super(props);
		this.state = {
			addressList: [],
			addressListCheck: [],
		}
		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);

	}

	componentWillMount () {
		this.props.navigation.setParams({
			addressList: this.state.addressList,
		})
	}

	componentDidMount () {
		const addressLists = this.props.navigation.state.params.addressList;
		if (addressLists && addressLists.length) {
			this._setAddress(addressLists);
		}
		DeviceEventEmitter.addListener('addressParamTwo', (res) => {
			const { addressList } = res;
			this._setAddress(addressList);
		});

	}

	_setAddress = (addresses) => {
		let { addressList } = this.state;
		if (addresses) {
			if (addresses.length === 1) {
				const companyAddress = addresses[0];
				if (typeof (companyAddress.index) != 'undefined') {
					if (companyAddress.index <= addressList.length) {  //修改
						addressList[companyAddress.index] = companyAddress;
					} else {
						addressList.push(companyAddress);
					}
				} else {
					if (addressList.length === 0) {
						companyAddress.index = 0;
					} else {
						companyAddress.index = addressList.length;
					}
					addressList.push(companyAddress);
				}
			} else {
				for (let i = 0; i < addresses.length; i++) {
					addressList[i] = addresses[i];
					addressList[i].index = i;
				}
			}
		}

		let newArr = Array.from(new Set(addressList));

		this.setState({
			addressList: newArr
		})

		this.props.navigation.state.params.addressList = addressList;
	}

	async _delItem (data) {
		const { addressList } = this.state;
		if (data.delType) {
			const params = {};
			params.companyAddress = data.companyAddress; //companyContactor
			params.bizType = 'COMPANY_ADDRESS_INFO'; //COMPANY_CONTACT_INFO
			const delResponse = await HTTP.POST(API_GENERATE(API.DELETE_COMPANY_INFO), params);
			if (delResponse) {
				addressList.splice(data.index, 1);
				console.log('del suc')
			} else {
				console.log('del fal')
			}
		} else {
			addressList.splice(data.index, 1);
		}

		this.setState({
			addressList
		})
		if (addressList.length < 1) {
			const { navigate } = this.props.navigation;
			const { responseData } = this.props.navigation.state.params;
			responseData.addressList = addressList;
			navigate('EnterpriseCreateAdditionInfo', {
				addressList,
				responseData
			});
		}
	}

	render () {
		let { addressList } = this.state;
		const addressView = addressList.map((companyAddress, index) => {
			const { detailAddress, checked, cityCode, cityName, provinceCode, provinceName, areaCode, areaName, addressName } = companyAddress;
			const source = checked ? selectedPicSourse : optionPicSourse;
			const areaText = (provinceCode ? provinceName : '') + (cityCode ? cityName : '') + (areaCode ? areaName : '');
			return (
				<View style={styles.row} key={index}>
					<View style={styles.rowMain} >
						<TouchableOpacity style={styles.rowMainLeft} onPress={() => {
							const address = addressList[index];
							address.checked = !address.checked;
							addressList[index] = address;
							this.setState({
								addressList
							});
						}}>
							<Image source={source} style={styles.circle} />
						</TouchableOpacity>

						<TouchableOpacity style={styles.rowMainRight} onPress={() => {
							const { navigate } = this.props.navigation;
							companyAddress.index = index;
							navigate('AddressAddPage', {
								goBack: 'AddressArrayPage',
								companyAddress,
								addressInfo: this.props.navigation.state.params.addressInfo
							});
						}}>
							{areaText ? <View style={styles.rowMainRow}><Text style={styles.text}>{areaText}</Text></View> : null}
							<View style={styles.rowMainRow}><Text style={styles.text}>{addressName || detailAddress}</Text></View>
						</TouchableOpacity>
					</View>

					<TouchableOpacity style={styles.rowSide} onPress={() => {
						/**
						 * delType 辨别是否已经提交到后台
						 * true 为已提交到后台，则删除时需要请求后台接口； false 未提交到后台 
						*/
						this._delItem({ companyAddress, delType: companyAddress.id ? true : false, index });
					}}>
						<Text style={[styles.text, { color: style.color.themeColor }]}>删除</Text>
					</TouchableOpacity>
				</View>
			)
		})

		return (
			<View style={[styles.container]}>
				<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>

					<View style={styles.wrap}>
						<View style={{ width: 345 * scale, }}>{addressView}</View>
					</View>

				</ScrollView >
				<LargeBtn onPress={this._didPressLargeBtn} text={'确定'} />
			</View>

		)
	}



	/**
 * 点击底部按钮
 */
	async _didPressLargeBtn () {
		const { navigate } = this.props.navigation;
		const { addressList } = this.state;

		navigate('EnterpriseCreateAdditionInfo', {
			addressList
		});
	}
}

const styles = StyleSheet.create({
	circle: {
		width: 14 * scale,
		height: 14 * scale,
	},
	row: {
		flexDirection: 'row',
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
	},
	rowSide: {
		width: 50 * scale,
		height: 70 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		// paddingTop: 15 * scale,
	},
	rowMain: {
		flex: 1,
		flexDirection: 'row',
	},
	rowMainLeft: {
		width: 25 * scale,
		height: 70 * scale,
		justifyContent: 'center',
	},
	rowMainRight: {
		flex: 1,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
	},
	rowMainRow: {
		flex: 1,
		flexDirection: 'row',
		// justifyContent: 'space-between',
		alignItems: 'center',
	},
	text: {
		fontSize: 14 * scale,
		color: '#4B4B4B'
	},
	scrollView: {
		flex: 1,

	},
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5',
	},
	wrap: {
		backgroundColor: '#fff',
		alignItems: 'center',
	},
})